package com.example.java.designpattern.builder;

import com.example.java.designpattern.Divisor;
import com.example.java.designpattern.RespChainDivisor;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author zengty
 * @apiNote
 * @date 2024/8/29
 * @project study
 */
public class RespChainDivisorBuilder implements DivisorBuilder{

    private final Collection<Divisor> divisors;

    public RespChainDivisorBuilder() {
        this.divisors = new ArrayList<>();
    }

    public RespChainDivisorBuilder(Collection<Divisor> divisors) {
        this.divisors = divisors;
    }

    public RespChainDivisorBuilder addDivisor(Divisor divisor) {
        this.divisors.add(divisor);
        return this;
    }

    public static RespChainDivisorBuilder withDivisors(Collection<Divisor> divisors) {
        return new RespChainDivisorBuilder(divisors);
    }

    @Override
    public Divisor build() {
        if (divisors.isEmpty()) {
            throw new RuntimeException("divisors is empty");
        }
        final RespChainDivisor header = new RespChainDivisor(null);
        RespChainDivisor pointer = header;
        for (Divisor divisor : divisors) {
            RespChainDivisor respChainDivisor = new RespChainDivisor(divisor);
            pointer.setNext(respChainDivisor);
            pointer = respChainDivisor;
        }
        return header.next();
    }
}
